package client;

import java.io.Serializable;

public class Download implements Serializable {

	private static final long serialVersionUID = -326009817168809203L;

	private final int mHashCode;

	public final String url;
	public final String remoteFile;
	public final String localFile;

	private long mBytesDownloaded;
	private long mBytesTotal;

	private boolean paused = true;
	private boolean justStarted = true;

	private DownloadTableModel model = null;
	private ComPeer downloader = null;

	public int row;

	public Download(String url, String remoteFile, String localFile) {
		this.url = url;
		this.remoteFile = remoteFile;
		this.localFile = localFile;
		mBytesTotal = -1;

		mBytesDownloaded = 0;

		mHashCode = remoteFile.hashCode();

		if (Client.DEBUG) {
			System.out.println("> Start file transfer: " + localFile);
		}

		this.model = model;
	}

	public void setlength(long length) {
		if (mBytesTotal < 0) {
			mBytesTotal = length;
		}
	}

	public void setDownloader(ComPeer com) {
		this.downloader = com;
	}

	public void setTableModel(DownloadTableModel model) {
		this.model = model;
	}

	public void updateDownload(int byteIncrement) {
		mBytesDownloaded += byteIncrement;

		if (Client.DEBUG) {
			System.out.println("> Appending data segment to file... "
					+ mBytesDownloaded + " of " + mBytesTotal);
		}

		int percentage = (int) (((double) mBytesDownloaded / (double) mBytesTotal) * 100);

		String state = "in progress";

		model.setValueAt(percentage, row, 2);

		if (isComplete()) {
			state = "complete";
			System.out.println("> End file transfer: " + localFile);
		}
		model.setValueAt(state, row, 1);
	}

	public void pause() {
		if (!isComplete() && downloader != null) {
			if (model != null) {
				model.setValueAt("paused", row, 1);
			}
			downloader.cancel();
			downloader = null;

			paused = true;
		}
	}

	public void start() {
		if (!isComplete() && downloader != null) {
			if (model != null) {
				model.setValueAt("start", row, 1);
			}
			paused = false;
		}
	}

	public void resume() {
		if (!isComplete() && downloader != null) {
			if (model != null) {
				model.setValueAt("resume", row, 1);
			}
			paused = false;
		}
	}

	public boolean isPaused() {
		return paused;
	}

	public boolean isComplete() {
		return mBytesDownloaded == mBytesTotal;
	}

	public long getProgress() {
		return mBytesDownloaded;
	}

	@Override
	public int hashCode() {
		return mHashCode;
	}

}
